import http from './interface';
import { getUserInfo } from '@/common/api/user';
import { uuid } from '../common';
import { useConfigStore, useUserInfoStore } from '@/store/index';

/**
 * 将业务所有接口统一起来便于维护
 * 如果项目很大可以将 url 独立成文件，接口分成不同的模块
 *
 */

const getToken = async function () {
    return await new Promise((resolve, reject) => {
        const configStore = useConfigStore();
        const userInfoStore = useUserInfoStore();

        uni.login({
            success: (data) => {
                let url = `${configStore.domain}/account/mall/api/login`
                if (configStore.debug) {
                    url = `${configStore.debugDomain}/account/mall/api/login`
                }
                let reqData = { code: data.code, puid: configStore.puid, type: configStore.platform }
                uni.request({
                    url: url,
                    method: 'POST',
                    data: reqData,
                    success: (response) => {
                        let { token, expire, jwttoken, is_login } = response.data.detail;

                        uni.setStorage({
                            key: 'token',
                            data: { token: token, jwttoken: jwttoken, expire: expire * 1000, created: (new Date()).getTime() },
                            success: () => {
                                resolve(token)
                            },
                            fail: () => {
                                reject('error')
                            }
                        })

                        if(is_login) {
                            try {
                                getUserInfo().then(res => {
                                    if (res.status === 0) {
                                        userInfoStore.setUserInfo(res.detail);
                                        uni.setStorage({
                                            key: 'userInfo',
                                            data: res.detail
                                        })
                                    }
                                })
                            } catch (err) { }
                        }
                    },
                    fail: (err) => {
                        reject(err)
                    }
                })
            },
            fail: (err) => {
                reject(err)
            }
        })
    })
}

// 单独导出(测试接口) import {test} from '@/common/vmeitime-http/'
export const request = (data) => {
    const configStore = useConfigStore();

    /* http.config.baseUrl = "http://localhost:8080/api/"*/
    //设置请求前拦截器
    http.interceptor.request = (config) => {
        let token = uni.getStorageSync('token')
        if (token && token.token && (new Date()).getTime() < token.expire + token.created) {
            //判断当前token是否过期
            config.header = {
                'Authorization': 'Token ' + token.token,
                'Platform': configStore.platform,
                'Version': configStore.version,
                'reqid': uuid()
            }
        } else {
            getToken().then(res => {
                config.header = {
                    'Authorization': 'Token ' + res,
                    'Platform': configStore.platform,
                    'Version': configStore.version,
                    'reqid': uuid()
                }
            })
        }
    }
    //设置请求结束后拦截器
    http.interceptor.response = (response) => {
        //判断返回状态 执行相应操作
        if (response.statusCode == 401) {
        }
        return response;
    }
    return http.request(data)
}
// 默认全部导出  import api from '@/common/vmeitime-http/'
export default {
    request,
    getToken
}
